package com.example.schoolguider.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.schoolguider.common.Result;
import com.example.schoolguider.common.ResultStatus;
import com.example.schoolguider.config.MinioTemplate;
import com.example.schoolguider.model.File;
import com.example.schoolguider.model.OssVO;
import com.example.schoolguider.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * @author wjc
 * @date 2024/7/1 9:48
 */
@RestController
@RequestMapping("/file")
public class FileController {
    public static final String NORM_DAY_PATTERN = "yyyy/MM/dd";

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private FileService fileService;

    private OssVO loadOssVO(OssVO ossVo) {
        String dir = DateUtil.format(new Date(), NORM_DAY_PATTERN)+ "/";
        String fileName = IdUtil.simpleUUID();
        ossVo.setDir(dir);
        ossVo.setFileName(fileName);
        return ossVo;
    }

    @PostMapping("/upload_minio")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.of(ResultStatus.SUCCESS, "上传失败，请选择文件");
        }
        OssVO oss = loadOssVO(new OssVO());
        minioTemplate.uploadMinio(file.getBytes(), oss.getDir() + oss.getFileName(), file.getContentType());
        return Result.of(ResultStatus.SUCCESS, oss);
    }

    @PostMapping("/insertFile")
    public Result insertFile(@RequestBody File file){
        return Result.of(ResultStatus.SUCCESS, fileService.insertFile(file));
    }

    @PostMapping("/list")
    public Result listFile(@RequestBody File file){
        return Result.of(ResultStatus.SUCCESS, fileService.listFile(file));
    }

}
